function isPC() {
    var userAgentInfo = navigator.userAgent.toLowerCase();
    var Agents = new Array("android", "iphone", "symbianOS", "windows phone", "ipad", "ipod");
    var flag = true;
    for (var v = 0; v < Agents.length; v++) {
        if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }
    }
    return flag;
}

Vue.component('scroll-view', {
    props: {
        viewWidth: Number,
        viewHeight: Number,
        barY: {
            type: String,
            default: 'defaultBar'
        },
        barX: {
            type: String,
            default: 'defaultBar'
        },
        deltaSize: {
            type: Number,
            default: 120
        },
        showTime: {
            type: Number,
            // -1 means forever
            default: 1000 
        },
        barInside: {
            type: Boolean,
            default: true
        },
        barWeight: {
            type: Number,
            default: 10
        },
        dragable: {
            type: Boolean,
            default: !isPC()
        },
        transition: {
            type: Boolean,
            default: true
        }
    },
    data: function() {
        return {
            childHeight: 0,
            childWidth: 0,
            curX: 0,
            curY: 0,
            view: null,
            barHide: false,
            scrollData: null,
            timer: null,
            
        }
    },
    template: `
        <div
            tabindex="0"
            :style="viewStyle" class="scroll-view"
            :class="{scrolling: scrollData, 'no-transition': !transition}"
            @mousedown.left="isPC() ? tryScroll($event) : null"
            @wheel="isPC() ? wheelOccur($event) : null"
            @touchstart="isPC() ? null : tryScroll($event)"
            @touchmove="isPC() ? null : scrollMove($event)"
            @touchend="isPC() ? null : scrollEnd($event)"

            @keydown.left="keydownFn($event, -deltaSize, true)"
            @keydown.right="keydownFn($event, deltaSize, true)"
            @keydown.up="keydownFn($event, -deltaSize, false)"
            @keydown.down="keydownFn($event, deltaSize, false)"

            >
            <slot v-bind:scroll="pos"></slot>
            <component
                :is="barX"
                v-show="barXNeeded"
                :cur="x"
                :total="totalWidth"
                :viewSize="viewWidth"
                :bar-hide="barHide"
                :weight="barWeight"
                direction="horizontal"
                key="scroll-view-bar-x"
                ref="barX"
                ></component>
            <component
                :is="barY"
                v-show="barYNeeded"
                :cur="y"
                :total="totalHeight"
                :viewSize="viewHeight"
                :bar-hide="barHide"
                :weight="barWeight"
                direction="vertical"
                ref="barY"
                key="scroll-view-bar-y"
                ></component>
            <div
                style="z-index: 9999; position: fixed; top: 0; left: 0; opacity: 0; width: 100%; height: 100%; cursor: move;"
                ref="scrollMovingListener"
                data-role="scroll-move-listener"
                @mousemove="isPC() ? scrollMove($event) : null"
                @mouseup.left="isPC() ? scrollEnd($event) : null"
                @mouseleave="isPC() ? scrollEnd($event) : null"
                v-show="this.scrollData"
            ></div>
        </div>
    `,
    computed: {
        
        pos: function() {
            return {
                transform: `translateZ(0) translate(${[-this.x + 'px', -this.y + 'px'].join(',')})`
            }
        },
        totalHeight: function() {
            return Math.max(this.childHeight, this.viewHeight);
        },
        totalWidth: function() {
            return Math.max(this.childWidth, this.viewWidth);
        },
        viewStyle: function() {
            return {
                width: this.curWidth + 'px',
                height: this.curHeight + 'px',
                overflow: 'hidden'
            }
        },
        curWidth: function() {
             return this.viewWidth + (this.barInside || !this.barYNeeded ? 0 : this.$refs.barY.weight);
        },
        curHeight: function() {
            return this.viewHeight + (this.barInside || !this.barXNeeded ? 0 : this.$refs.barX.weight);
        },
        x: {
            get: function() {
                return Math.max(
                    Math.min(
                        this.totalWidth - this.viewWidth,
                        this.curX
                    ), 0
                )
            },
            set: function(nv) {
                this.autoFadeOut();
                this.curX = Math.max(
                    Math.min(
                        this.totalWidth - this.viewWidth,
                        nv
                    ), 0
                )
            }
        },
        y: {
            get: function() {
                return Math.max(
                    Math.min(
                        this.totalHeight - this.viewHeight,
                        this.curY
                    ), 0
                )
            },
            set: function(nv) {
                this.autoFadeOut();
                this.curY = Math.max(
                    Math.min(
                        this.totalHeight - this.viewHeight,
                        nv
                    ), 0
                )
            }
        },
        barYNeeded: function() {
            return this.barY && this.barY != 'none' && this.totalHeight > this.viewHeight;
        },
        barXNeeded: function() {
            return this.barX && this.barX != 'none' && this.totalWidth > this.viewWidth;
        },
        hasBar: function() {
            return this.barYNeeded || this.barXNeeded;
        }
    },
    methods: {
        isPC: isPC,
        autoFadeOut: function() {
            clearTimeout(this.timer);
            this.timer = null;
            this.barHide = false;
            if (this.showTime > 0) {
                this.timer = setTimeout(() => {
                    this.barHide = true;
                    this.timer = null;
                }, this.showTime);
            }
                
        },
        wheelOccur: function(e) {
            if (this.hasBar) {
                e.preventDefault();
                e.stopPropagation();
            }
            
            var delta = e.wheelDelta ? (e.wheelDelta / 120) : (-e.detail / 3),
                plus = delta * this.deltaSize;
            var horizontal = e.target === this.$refs.barX.$el;
            if (this.totalHeight <= this.viewHeight) {
                horizontal = true;
            }
            this.updatePosition(-plus, horizontal);
            
        },
        
        tryScroll: function(e) {
            if (!this.dragable || !this.hasBar) {
                this.scrollData = null;
                return;
            }
            if (this.scrollData) {
                return;
            }

            var {clientX, clientY} = e.touches ? e.touches[0] : e;
            var scrollData = {
                startEvent: e,
                isBar: e.target === this.$refs.barX.$el || e.target === this.$refs.barY.$el,
                clientX, clientY
            }, direction = null;

            if (e.target === this.$refs.barX.$el) {
                direction = 'horizontal';
            } else if (e.target === this.$refs.barY.$el) {
                direction = 'vertical';
            } else {
                direction = 'both';
            }

            this.scrollData = Object.assign({direction}, scrollData);
        },
        scrollMove: function(e) {
            if (!this.dragable || !this.scrollData) {
                return;
            } else {
                e.stopPropagation();
                e.preventDefault();
                var {clientX, clientY} = e.touches ? e.touches[0] : e;
                var cx = clientX - this.scrollData.clientX,
                    cy = clientY - this.scrollData.clientY;
                this.scrollData.clientX = clientX;
                this.scrollData.clientY = clientY;
                // console.log(cx, cy);
                if (this.scrollData.direction == 'vertical' || this.scrollData.direction == 'both') {
                    this.updatePosition((this.scrollData.isBar ? 1 : -1) * cy / this.$refs.barY.rate, false);
                }
                if (this.scrollData.direction == 'horizontal' || this.scrollData.direction == 'both') {
                    this.updatePosition((this.scrollData.isBar ? 1 : -1) * cx / this.$refs.barX.rate, true);
                }
            }
        },
        scrollEnd: function(e) {
            
            
            if (!this.dragable || !this.scrollData) {
                return;
            } else {
                var scrollData = this.scrollData;
                this.scrollData = null;
                if (e.timeStamp - scrollData.startEvent.timeStamp < 300) {
                    if (scrollData.isBar) {
                        this.$nextTick(() => {
                            var x = scrollData.clientX, y = scrollData.clientY;
                            var target = scrollData.startEvent.target;
                            var msg = target.getBoundingClientRect();
                            var percent = {
                                x: (x - msg.left) / msg.width,
                                y: (y - msg.top) / msg.height
                            }, direction = scrollData.direction;
                            this.reposition(percent, direction != 'vertical');
                        });
                    }
                }
                
                
            }
        },

        keydownFn: function(e, plus, horizontal) {
            if (this.barXNeeded && horizontal || this.barYNeeded && !horizontal) {
                e.stopPropagation();
                e.preventDefault();
            }
            this.updatePosition(plus, horizontal);
        },

        reposition: function(percent, horizontal) {
            
            
            if (!horizontal) {
                var vm = this.$refs.barY;
                this.updatePosition(percent.y * this.totalHeight - this.viewHeight / 2 - this.y, false);
            } else {
                var vm = this.$refs.barX;
                this.updatePosition(percent.x * this.totalWidth - this.viewWidth / 2 - this.x, true);
            }
        },

        updatePosition: function(plus, horizontal) {
            if (!horizontal) {
                this.y = this.y + plus;
                return true;
            } else {
                this.x = this.x + plus;
                return true;
            }
        },

    },
    created: function() {
        var vm = this;
        this.$nextTick(function() {
            // console.log('scroll-view created', vm, vm.$children[0]);
            vm.view = vm.$children[0];
            vm.view.$watch('totalHeight', function(newValue, oldValue) {
                vm.childHeight = newValue;
            });
            vm.view.$watch('totalWidth', function(newValue, oldValue) {
                vm.childWidth = newValue;
            });

            vm.view.$watch('totalHeight', vm.autoFadeOut);
            vm.view.$watch('totalWidth', vm.autoFadeOut);

            vm.childHeight = vm.view.totalHeight;
            vm.childWidth = vm.view.totalWidth;

           document.querySelector('body').appendChild( vm.$refs.scrollMovingListener );
        })
    },
    components: {
        defaultBar: {
            props: ['cur', 'total', 'viewSize', 'direction', 'weight', 'barHide'],
            template: `
            <div
                class="bar-area bar-default"
                :class="[direction == 'vertical' ? 'vertical' : 'horizontal']"
                :style="barStyle"
                :title="curPercent * 100 + '%'"
            >
                <div :style='style' class="bar"></div>
            </div>
            
            `,
            computed: {
                curPercent: function() {
                    return this.total == this.viewSize ?
                        1 : Math.floor(this.cur / (this.total - this.viewSize) * 100) / 100;
                },
                barStyle: function() {
                    return Object.assign(
                        this.barHide ? {} : {opacity: 1},
                        {
                            [this.direction == 'vertical' ? 'width' : 'height']: this.weight + 'px'
                        }
                    )
                },
                rate: function() {
                    return this.viewSize / this.total;
                },
                barSize: function() {
                    return this.rate * this.viewSize;
                },
                curPos: function() {
                    return this.cur * this.rate;
                },
                style: function() {
                    return Object.assign(
                        this.direction == 'vertical' ?
                            {height: this.barSize + 'px', transform: `translateZ(0) translateY(${this.curPos + 'px'})`} :
                            {width: this.barSize + 'px', transform: `translateZ(0) translateX(${this.curPos + 'px'})`}
                    );
                }
            }
        },
    },
});